$(function() {
    var height = $(window).height()-160;
    var _this = null;
    var vue = new Vue({
        el: '#app',
        data: {
            styleSize:constants.styleSize,
            fullScreenloading: false,
            loadMsg:'加载中。。。',
            ws:null,
            sendUser:{
                userBh:'',
                userName:''
            },
            formData:{
                content:''
            },
            chatUserList:[],
            msgList:[],
            toUser:'',
            timeoutObj:null,
            connectModal:false,
            editRuleValidate: {
                userBh:{required:true,message:'请输用户Id',trigger: 'blur'},
                userName:{required:true,message:'请输用户昵称',trigger: 'blur'}
            },
        },
        created:function(){
        },
        mounted :function(){
            var _this = this;
            this.connectServer();
            this.startHeart();
            this.ueditor = UE.getEditor('editor',{
                toolbars: [
                    ['emotion']
                ],
                wordCount:false,                //统计字数
                elementPathEnabled:false,       //元素路径
                enableAutoSave:false,           //自动保存
            });
            this.ueditor.ready(function() {
                $(".edui-editor-messageholder.edui-default").css({ "visibility": "hidden" });
                _this.ueditor.setHeight(170);

                _this.ueditor.setContent("<span></span>")
                _this.ueditor.focus()
            });
            //监听浏览器关闭，关闭前先关闭webSocket
            window.onbeforeunload = function () {
                if(null != this.ws){
                    this.ws.close();
                }
            };
        },
        methods: {
            openConnectWin(){
                this.sendUser.userBh = "";
                this.sendUser.userName = "";
                this.connectModal = true;
            },
            cancelFunc(){
                this.connectModal = false;
            },
            connectServer(userBh, userName){
                var _this = this;
                this.$refs['editValidate'].validate((valid) => {
                    if (valid) {
                        if (null == this.ws) {
                            var urlPrefix = 'ws://121.41.46.175:5270/ljp/connect/';
                            var url = urlPrefix + "/" + this.sendUser.userBh + "/" + this.sendUser.userName;
                            this.ws = new WebSocket(url);
                            this.connectModal = false;
                            this.ws.onopen = function () {
                                console.log("建立 websocket 连接...");
                            };
                            this.ws.onmessage = function (event) {
                                //服务端发送的消息
                                //console.log(event);
                                var data = JSON.parse(event.data);
                                //console.log(data);
                                if (null != data && (data.type == 1 || data.type == 2)) { //聊天信息
                                    var msg = data.msg;
                                    if (data.sendUserBh == _this.sendUser.userBh) {
                                        if (data.type == 1) {  //公共聊天信息
                                            msg = "<div class=\"triangle-right\"></div><div class='userTitleSelf'>" + _this.sendUser.userName + "</div> " +
                                                '<div class="selfMsgContent">' + msg + '</div>';
                                        }
                                        if (data.type == 2) {   //私人聊天信息
                                            msg = "<div class=\"triangle-right\"></div><div class='userTitleSelf'><span class='private'>私</span>" + _this.sendUser.userName + "</div> " +
                                                '<div class="selfMsgContent">' + msg + '</div>';
                                        }
                                        _this.msgList.push("<div class='fr'>" + msg + "</div><div class='clearfix'></div>");
                                    } else {
                                        if (data.type == 1) {  //公共聊天信息
                                            msg = "<div class=\"triangle-left\"></div><div class='userTitleOther'>" + data.sendUserXm + "</div> " +
                                                '<div class="otherMsgContent">' + msg + '</div>';
                                        }
                                        if (data.type == 2) {   //私人聊天信息
                                            msg = "<div class=\"triangle-left\"></div><div class='userTitleOther'>" + data.sendUserXm + "<span class='private'>私</span></div> " +
                                                '<div class="otherMsgContent">' + msg + '</div>';
                                        }
                                        _this.msgList.push("<div class='fl'>" + msg + "</div><div class='clearfix'></div>");
                                    }
                                    //+'<img src="../../static/image/happy.png" class="icon"/>'
                                }
                                //刷新在线列表
                                if (null != data && data.type == 4) {
                                    _this.chatUserList = data.onlineUserList;
                                }

                                //用户进入聊天室
                                if (null != data && data.type == 5) {
                                    msg = "<div class='welcome'>用户[" + (data.sendUserXm) + "]进入了聊天室!</div>";
                                    _this.msgList.push(msg);
                                }

                                //用户离线
                                if (null != data && data.type == 3) {
                                    msg = "<div class='warning'>用户[" + (data.sendUserXm) + "]已经离开聊天室!</div>";
                                    _this.msgList.push(msg);
                                }

                                _this.toBottom();
                            };
                            this.ws.onclose = function (event) {
                                _this.ws = null;
                                _this.chatUserList.splice(0, _this.chatUserList.length);
                                _this.toBottom();
                            }
                            this.ws.onerror = function (event) {
                                //console.log(event.data);
                                _this.ws = null;
                                _this.sendUser = {
                                    userBh: '',
                                    userName: ''
                                }
                            };
                        } else {
                            this.$Message.error("已经建立服务器连接，请不要重复连接");
                        }
                    }
                });
            },
            quitServer(){
                if(null != this.ws){
                    this.ws.close()
                    this.ws = null;
                }
            },
            toBottom(){
                setTimeout(function(){
                    $('.chatView').scrollTop($('.chatView').get(0).scrollHeight+150);
                },200)
            },
            sendMsg(){
                var _this =this;
                if(null != this.ws) {
                    var content = this.ueditor.getContent();
                    if (null == content || "" == content.trim()) {
                        this.$Message.error("请输入聊天信息");
                        return;
                    }
                    content = content.trim();
                    if(null == this.toUser || this.toUser == ""){
                        this.ws.send(content)
                    }else{
                        var sendUserBh = this.sendUser.userBh;
                        var url = "/privateSend/"+sendUserBh+"/to/"+this.toUser+"?message="+content
                        commonFunc.submit(url,"get",{},function(data){
                            if(data.code != "100"){
                                _this.$Message.error("发送信息失败");
                            }
                        },function(data){
                            _this.$Message.error("发送信息失败");
                        });
                    }
                    this.ueditor.setContent("")
                    this.ueditor.focus(true);
                    $("#ueditor_0").html("");
                }else{
                    this.$Message.error("请先点击【连接服务器】建立网络连接");
                }
            },
            chooseUser(toUser){
                if(toUser != this.sendUser.userBh){
                    this.toUser = toUser;
                }
            },
            clearChooseUser(){
                if(null != this.toUser && '' != this.toUser){
                    this.toUser='';
                }else{
                    this.$Message.error("您未选择私聊用户");
                }
            },
            startHeart: function () {   //设置心跳程序，避免nginx(设置的5分钟)超时断开长连接
                var _this = this;
                this.timeoutObj && clearTimeout(this.timeoutObj);
                this.timeoutObj = setTimeout(function () {
                    //这里发送一个心跳，后端收到后，返回一个心跳消息，
                    //onmessage拿到返回的心跳就说明连接正常
                    if(null != _this.ws){
                        _this.ws.send("HeartBeat");
                        console.log('ping');
                        _this.startHeart();
                    }
                }, 5*60*1000)
            }
        }
    });
    //此处将vue对象作用域上提至window返回，用户实现ueditor的crtl+enter事件
    window.vue = vue;
});
